package main

import (
	goredislib "github.com/go-redis/redis/v8"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
	"mxshop_srvs/inventory_srv/global"
	"mxshop_srvs/inventory_srv/initialize"
	"mxshop_srvs/inventory_srv/model"
	"sync"
)

func main() {
	initialize.InitConfig()
	initialize.InitDB()
	client := goredislib.NewClient(&goredislib.Options{
		Addr: "127.0.0.1:6379", // 这个自己修改成redis的ip地址
	})
	pool := goredis.NewPool(client) // or, pool := redigo.NewPool(...)

	rs := redsync.New(pool)

	gNum := 20 // 启动2个协程

	mutexname := "goods_1" // 假设以goods的id来命名锁
	var wg sync.WaitGroup
	wg.Add(gNum)
	for i := 0; i < gNum; i++ {
		go func() {
			defer wg.Done()
			var inv model.Inventory
			mutex := rs.NewMutex(mutexname)
			if err := mutex.Lock(); err != nil {
				panic(err)
			}
			_ = global.DB.Where(&model.Inventory{Goods: 1}).First(&inv)

			inv.Stocks -= 1
			// 一旦使用了事务的，保存修改数据库的操作就需要使用事务的tx，而不能使用db
			global.DB.Save(&inv)

			if ok, err := mutex.Unlock(); !ok || err != nil {
				panic("unlock failed")
			}
		}()
	}
	wg.Wait()
}